package com.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 *
 * @author hh
 * @since 2023/5/28
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        LockCache lockCache = new LockCache();
        for (int i = 0; i < 5; i++) {
            int temp = i;
            new Thread(() -> {
                lockCache.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            int temp = i;
            new Thread(() -> {
                lockCache.get(temp + "");
            }, String.valueOf(i)).start();
        }
    }
}

class LockCache {
    private volatile Map<String, String> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, String value) {
        // 写入的时候只有一个线程写
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入ok");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        // 读时候可以有多个线程来读
        readWriteLock.readLock().lock();
        try {
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
